package com.cacode.androidShell;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.location.LocationManager;
import android.os.Build;
import android.provider.Settings;
import android.support.annotation.RequiresApi;
import android.view.Window;
import android.webkit.CookieManager;
import android.webkit.JavascriptInterface;
import android.webkit.WebStorage;
import android.webkit.WebView;
import android.widget.Toast;

import java.io.File;
import java.util.Objects;

/**
 * 这里是前端js调用的公共方法
 * <p>
 * 需要全部在this.run()方法执行
 */
public class JavaMethods {

    private final WebView wv;
    private final Activity activity;

    public JavaMethods(WebView wv, Activity activity) {
        this.wv = wv;
        this.activity = activity;
    }

    /**
     * 刷新页面缓存
     */
    @JavascriptInterface
    public void refresh() {
        this.run(() -> {
            wv.clearCache(true);
            wv.reload();
        });
    }

    /**
     * 刷新缓存达到更新的目的
     */
    @JavascriptInterface
    public void update() {
        this.run(() -> {
            File file = activity.getCacheDir();
            if (file != null && file.exists() && file.isDirectory()) {
                for (File item : Objects.requireNonNull(file.listFiles())) {
                    item.delete();
                }
                file.delete();
            }
            activity.deleteDatabase("webview.db");
            activity.deleteDatabase("webviewCache.db");
            final Intent intent = activity.getPackageManager().getLaunchIntentForPackage(activity.getString(R.string.app_name));
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            activity.startActivity(intent);
        });
    }

    /**
     * 刷新缓存达到更新的目的
     */
    @JavascriptInterface
    public void download(String url) {
        this.run(() -> {
            WebviewUtil.openBrowser(this.activity, url);
        });
    }

    /**
     * 退出登录
     */
    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @JavascriptInterface
    public void logout() {
        this.run(() -> {
            CookieManager.getInstance().removeAllCookies(value -> wv.reload());
            CookieManager.getInstance().flush();
            WebStorage.getInstance().deleteAllData();
        });
    }

    /**
     * 重新加载
     */
    @JavascriptInterface
    public void reload() {
        this.run(wv::reload);
    }

    /**
     * 设置标题栏颜色
     */
    @JavascriptInterface
    public void setStatusBarColor(String color) {
        this.run(() -> {
            Window window = activity.getWindow();
            window.setStatusBarColor(Color.parseColor(color));
        });
    }

    /**
     * 将操作在主程序执行
     *
     * @param runnable
     */
    private void run(Runnable runnable) {
        activity.runOnUiThread(runnable);
    }
}